package com.shopmall.user.service.Impl;

import com.alibaba.fastjson.JSON;
import com.shopmall.common.exception.CustomException;
import com.shopmall.model.dto.h5.UserLoginDto;
import com.shopmall.model.dto.h5.UserRegisterDto;
import com.shopmall.model.entity.user.UserInfo;
import com.shopmall.model.vo.common.ResultCodeEnum;
import com.shopmall.model.vo.h5.UserInfoVo;
import com.shopmall.user.mapper.UserInfoMapper;
import com.shopmall.user.service.UserInfoService;
import com.shopmall.utils.AuthContextUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public String register(UserRegisterDto userRegisterDto) {
        // userRegisterDto获取数据
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        String code = userRegisterDto.getCode();
        // 从redis中获取验证码校检
        String redisCode = redisTemplate.opsForValue().get(username);
        assert redisCode != null;
        if (!redisCode.equals(code)) {
            throw new CustomException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        // 校检用户名不能重复
        UserInfo userInfo = userInfoMapper.selectByUsername(username);
        if (userInfo != null) {
            throw new CustomException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }
        // 封装添加数据，调用方法添加数据库
        userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setNickName(nickName);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setPhone(username);
        userInfo.setStatus(1);
        userInfo.setSex(0);
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        userInfoMapper.save(userInfo);
        // 从redis三处发送的验证码
        redisTemplate.delete(username);
        return "ok";
    }

    // 会员登录
    @Override
    public String login(UserLoginDto userLoginDto) {
        // 获取参数中用户名和密码
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();
        // 根据用户名查询数据库，得到用户信息
        UserInfo userInfo = userInfoMapper.selectByUsername(username);
        if (userInfo == null) {
            throw new CustomException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 比较密码是否一致
        String database_password = userInfo.getPassword();
        String md5_password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!database_password.equals(md5_password)) {
            throw new CustomException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 校检用户是否禁用
        if (userInfo.getStatus() == 0) {
            throw new CustomException(ResultCodeEnum.ACCOUNT_STOP);
        }
        // 生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        // 把用户信息放到redis里面
        redisTemplate.opsForValue().set("user:" + token, JSON.toJSONString(userInfo), 7, TimeUnit.DAYS);
        return token;
    }

    // 获取当前登录用户信息
    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
        // 从redis根据token获取用户信息
//        String userJson = redisTemplate.opsForValue().get("user:" + token);
//        if (!StringUtils.hasText(userJson)) {
//            throw new CustomException(ResultCodeEnum.LOGIN_AUTH);
//        }
//        UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }
}
